﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PeerToPeer
{
    public partial class FrmUpdServer : Form
    {
        public FrmUpdServer()
        {
            InitializeComponent();
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
            Task.Run(new Action(() => { Start(); }));
        }
        private void Start()
        {
            UdpClient tcpListener = new UdpClient(3722);         
            //tcpListener.Connect(IPAddress.Parse("127.0.0.1"), 3721);  
            PushMsg($"启动侦听！\r\n");
            while (true)
            {
                IPEndPoint remoteIpEndPoint1 = null;
                IPEndPoint remoteIpEndPoint2 = null;
                var bytes = tcpListener.Receive(ref remoteIpEndPoint1);
                var remoteEndPoint1 = remoteIpEndPoint1.ToString();
                PushMsg($"{remoteEndPoint1}连接上我了！\r\n");
                bytes = tcpListener.Receive(ref remoteIpEndPoint2);
                var remoteEndPoint2 = remoteIpEndPoint2.ToString();
                PushMsg($"{remoteEndPoint2}连接上我了！\r\n");
                 bytes = Encoding.UTF8.GetBytes(remoteEndPoint2);
                tcpListener.Send(bytes, bytes.Length, remoteIpEndPoint1);
                PushMsg($"{remoteEndPoint2}转发出去了！\r\n");
                bytes = Encoding.UTF8.GetBytes(remoteEndPoint1);
                tcpListener.Send(bytes, bytes.Length, remoteIpEndPoint2);
                PushMsg($"{remoteEndPoint1}转发出去了！\r\n");
                PushMsg($"继续等待下一轮！---------\r\n");
            }
        }
        private void PushMsg(string Msg)
        {
            this.BeginInvoke(new Action(() =>
            {
                rtb_Msg.AppendText(Msg);
            }));
        }
    }
}
